package com.tanhua.management.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.AdminMapper;
import com.tanhua.common.pojo.Admin;
import com.tanhua.common.utils.AdminThreadLocal;
import com.tanhua.management.vo.ProfileVo;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SystemService {

    @Autowired
    private AdminMapper adminMapper;

    @Value("${jwt.secret}")
    private String secret;

    public Admin findadmin(String username, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        Admin admin = this.adminMapper.selectOne(queryWrapper);
        String word= DigestUtils.md5Hex(password);
        if (word.equals(admin.getPassword())){
            return admin;
        }
        return null;
    }

    public String getToken(String username, String password, String uuid) {
        Admin admin = this.findadmin(username, password);
        if (null==admin){
            return "用户名或者密码错误";
        }
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("id", admin.getId());
        // 生成token
        String token = Jwts.builder()
                .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                .compact();


        return token;
    }


    public ProfileVo queryByToken() {
        try {
/*            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

          String id= body.get("id").toString();
            Admin admin = adminMapper.selectById(id);*/
            Admin admin = adminMapper.selectById(AdminThreadLocal.get().getId());
            ProfileVo profileVo=new ProfileVo();
            profileVo.setUid(String.valueOf(admin.getId()));
            profileVo.setUsername(admin.getUsername());
            profileVo.setAvatar(admin.getAvatar());

            return profileVo;
        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ " );
        } catch (Exception e) {
            log.error("token不合法！ ", e);
        }



        return null;
    }

    public boolean exit() {
        try {
            AdminThreadLocal.remove();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }
}
